#!/bin/bash
#THIS DRIVER WRITTEN BY MATTHEW VONA ARB FOR THE HAMPSHIRE CONTROLS
# MODEL 140 Temperature Sentry
#FOR QUESTIONS WRITE mailto:mvona@arb.ca.gov
#-------------------------------------------------------------
#!/usr/bin/env bash
# THIS IS THE FUNCTION CALLED IN THE EVENT THAT CTRL+C IS PRESSED
cleanup()
{
    echo "Caught Signal ... cleaning up."
        if !(rm -f Data/.locked > /dev/null); then
	        exit 1
        fi
    for i in `pgrep -P ${plotterid}`; do
    	kill -9 ${i}
	done
	kill -9 ${plotterid}
	echo "Done cleanup ... quitting."
    exit 0
}
#########################################################################################
#						END MAIN DISPLAY FUNCTION.										#
#########################################################################################	
	
#THIS IS THE RELATIVE DIRECTORY VARIABLE 
DIR="$( cd -P "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

###############################################################
# BEGIN DISPLAY FUNCTION : MJV 11/15/2013                         #
###############################################################
#read config file
while read line; do	
	eval $line
done < Config/config
if [ -z $no_plots ]; then
	bash ${DIR}/plotter.sh 1>/dev/null 2>/dev/null &	
	plotterid="$!"
	echo "$plotterid"
fi	

#########################################################################################
#						BEGIN MAIN DISPLAY FUNCTION.									#
#########################################################################################
#BEGIN DIAGNOSTICS SECTION																#
#########################################################################################
diag()
{
	this_name=$(cat ${DIR}/.usr$instance | grep -o "\-r [A-Za-z0-9]*" | awk '{ print $2 }')
	thishour=`date "+%H"`
	thisalert="errors$thishour"
	it=`sed 's/ITEMP=/ /g' | sed 's/:::/ /g' | awk 'BEGIN {if ($2!="" && $2!=" ") print $2+0}'`
	upper=40
	lower=15
	awk -v name="$this_name" -v upper="$upper" -v lower="$lower" -v it="$it" -v stamp="$timestamp" 'BEGIN {if (it!="" && it>upper || it!="" && it<lower ) print stamp":::The indoor ITEMP is higher than 40C or less than 15C "it ;}'>>"Data/${thisalert}"
}


#BEGIN WRITE
#THIS FUNCTION HANDELS READ RIGHT HANDSHAKES BETWEEN VARIOUS DRIVERS
#IN GENERAL, THE DATA IS PLACED IN THE VARIABLE $TIMESTAMP PRIOR TO CALL
#NEXT, IT OPENS THE DATA DIRECTORY AND LOOKS FOR THE .locked FILE
#IF IT EXISTS, IT HANGS OUT UNTIL IT DOESN'T EXIST. AT THAT POINT
#IT CREATES A .locked FILE, AND APPENDS TO THE DATA RECORD.
#FINALLY IT REMOVES THE .locked FILE IT HAS CREATED.
#THIS FUNCTION ALSO PARSES THE .DISABLED FILE IN THE DRIVER FOLDER
#AND TAKES A CHANNEL OFF LINE BY PREPENDING --DISABLED-- TO EACH LINE OF CONTENT IN THE DATA DIRECTORY
#written by MJV
write()
{
#CONFIRM THAT THERE IS NO HIDDEN FILE CALLED '.locked'
	while [ -e "Data/.locked" ];
		do
			sleep .2;
		done	
	echo "LOCKED" > "Data/.locked";
	#PARSE THE .disabled File
	channel_status=`cat "${DIR}/.disabled${instance}"`
	#IF THE FILE DOSEN'T EXIT OR IS NOT ACCESIBLE
	#POPULATE DISPLAY

	source sys_resources/translate_code.sh displaycode $channel_status rawcode

	errorsfile="Data/errors"`date "+%H"`
	if !(echo "$data" | sed 's/^/'$timestamp'/g'| sed 's/$/'$target_value'/g' |tee -a "Data/$datafile" | diag); then
		echo "GENERAL FAILURE WRITING TO RECORD: $#";
		cleanup;
	fi

	if !(rm -f "Data/.locked" > /dev/null); then
			echo "GENERAL FAILURE REMOVING LOCK: $#";
			exit 1;	
	fi
	if !(timestamp="" && data=""); then
		echo "GENERAL FAILURE CLEARING WRITE BUFFER: $#";
		cleanup;
	fi	
}

#THIS IS THE ACTUAL COMMUNICATION WITH THE INSTRUMENT
#THE TIMER CONTROL. AT THE BEGINING IT TESTS FOR THE 
#EXISTENCE IF TOGGLE VARRIABLES WHICH ARE UTILIZED BOTH BY
#THE COMM ROUTINE runit() AND THE DIAGNOSTICS DATA ROUTINE
#diag()
runit()
{
#IF THE -d, -C, or -p variable is set to on, then append those parameters
#to the sjinn communication string. If the -i parameter is passed, diag will
#test for IZS specific routines.
if [ "$izs_val" = "on" ]; then
	izs="on"
fi
if [ "$dtr_val" = "on" ]; then
 	dtr="--dtr" 
fi
if [ "$ctr_val" = "on" ]; then
 	ctr="--ctr"
fi
if [ "$p8n1_val" = "on" ]; then
 	p8n1="-p8n1"
fi
#Date stamp
today=`date "+%Y-%d-%m"`
timestamp=$rprt_nm::`date "+%m-%d-%Y_%H:%M"`:::
#THIS IS THE NAME OF THE DATA FILE RIGHT NOW
first=''
second=''
data=''
datafile="$saroad-$today"
#TALK TO THE INSTRUMENT, PRE-APPEND THE TIMESTAMP AND REPORTING NAME TO EACH
#WAIT FOR THE INSTRUMENT TO RESPOND.
#LINE OF OUTPUT AND tee TO THE DATA FILE, then pass to the diag routine.
data=`timeout 20 sjinn -b$bd_rt -d $dvc_prt -s "otemp\r" -r40 -w6` 
#COMPARE THE FIRST AND SECOND VALUE PROVIDED BY THE TEMP SENSOR
#temp=26.5 repeat=26.5
first=`echo $data | grep -o temp=[+,-,0-9][0-9][*,.][0-9] | sed 's/temp=//g'`
second=`echo $data | grep -o repeat=[+,-,0-9][0-9][*,.][0-9] | sed 's/repeat=//g' `
if [ -z $first ]; then
		sleep 2
		data=`timeout 20 sjinn -b$bd_rt -d $dvc_prt -s "otemp\r" -r40 -w6` 	
		first=`echo $data | grep -o temp=[+,-,0-9][0-9][*,.][0-9] | sed 's/temp=//g'`
		second=`echo $data | grep -o repeat=[+,-,0-9][0-9][*,.][0-9] | sed 's/repeat=//g' `
		if [ -z $first ]; then
			sleep 2
			data=`timeout 20 sjinn -b$bd_rt -d $dvc_prt -s "otemp\r" -r40 -w6` 	
			first=`echo $data | grep -o temp=[+,-,0-9][0-9][*,.][0-9] | sed 's/temp=//g'`
			second=`echo $data | grep -o repeat=[+,-,0-9][0-9][*,.][0-9] | sed 's/repeat=//g' `		
				if [ -z $first ]; then
					sleep 2
					data=`timeout 20 sjinn -b$bd_rt -d $dvc_prt -s "otemp\r" -r40 -w6` 	
					first=`echo $data | grep -o temp=[+,-,0-9][0-9][*,.][0-9] | sed 's/temp=//g'`
					second=`echo $data | grep -o repeat=[+,-,0-9][0-9][*,.][0-9] | sed 's/repeat=//g' `		
					fi
			
			fi
fi
if [[ $first != $second ]]; then
		:
else
		data=`echo ITEMP=$first`
		write
fi
}

#THIS IS THE FUNCTION RUN IN THE EVENT THAT THE REQUIRED PARAMETERS
#ARE NOT ENTERED.
usage()
{
clear
cat << EOF
usage: $0 options
OPTIONS:
-h	display help
-n	the device identifier
-r	rprt_nm [rn]
-d	dvc_prt [eg, /dev/ttyS0, /dev/ttyUSB1] 
-b	bd_rt [2400,4800,9600,etc.]
-w	wt_rsp1 [seconds]
-s	SAROAD number of the station
-t	[on/off] (OPTIONAL)
-C	[on/off] (OPTIONAL)
-p	[on/off] (OPTIONAL)
Last updated 7/28/2009
EOF
}
#HELP FUNCTION GIVES BACKGROUND ON THIS DRIVER
help_me ()
{
clear
cat .help
exit 0
}
def_opts ()
{
clear
cat .options
}

##CLEAR ALL VARIABLES               
rprt_nm= ; dvc_prt= ; bd_rt= ; cmnd1= ; wt_rsp1= ; bd_rt= ; rsp_lngth= ; izs_val= ;
dvc_prt= ; frqncy= ; dtr= ; ctr= ; p8n1= ; izs= ; saroad= ; p8n1= ; id_nmbr= ; instance=1
##INITIALIZE THE BUFFER
return='NOT WRITTEN TO'
##loop through all variables and parameters
##Note that the position of the colon indicates the presence
##of a parameter to collect. The h parameter simply
##returns the help message.

while getopts “hn:i:r:s:d:b:c:w:l:t:C:p:I:” OPTION
do
case $OPTION in
n)
id_nmbr=$OPTARG
;;
a)
abs_path=$OPTARG
;;
I)
instance=$OPTARG
;;
s)
saroad=$OPTARG
;;
r)
rprt_nm=$OPTARG
;;
d)
dvc_prt=$OPTARG
;;
b)
bd_rt=$OPTARG
;;
c)
cmnd1=$OPTARG
;;
w)
wt_rsp1=$OPTARG
;;
l)
rsp_lngth=$OPTARG
;;
t)
dtr_val=$OPTARG
;;
C)
ctr_val=$OPTARG
;;
p)
p8n1_val=$OPTARG
;;
h)
help_me
exit 1
;;
*)
usage
exit 1
;;
esac
done
#CHECK FOR THE CRITICAL PARAMETERS, IF THEY ARE NOT PRESENT THEN
#RUN THE USAGE FUNCTION WHICH RETURNS THE INSTRUCTIONS FOR PROPER USAGE
#MUST HAVE r n d b c w l i s
if [ -z "$dvc_prt" ] || [ -z "$bd_rt" ] || [ -z "$saroad" ] 
	then
		usage
		exit
fi
	#INITIALIZED THE RAN VARIABLE. THIS IS USED TO TOGGLE THE TIMER GATE
ran=0
	#TRAP CTRL+C
trap cleanup 1 2 3 6 15
	#SETUP THE OPERATING LOOP
while :
do
second=`date "+%S"`
if [ "$second" -eq "00" ] && [ "$ran" -eq "0" ]; then
	#RUN THE RUNIT FUNCTION
	runit
	#TOGGLE THE RAN VARIABLE SO THAT THE PROCESS WILL NOT REPEAT
	#UNTIL THE BEGINNING OF THE NEXT MINUTE.
	ran=1
	#WAIT FOR COMPLETION OF THE RUNIT FUNCTION AND THE VARIABLE
	#SET
	sleep 1
	#AND WAIT ONE SECOND BEFORE CHECKING AGAIN
else 
	#WAIT ONE SECOND
	sleep .5
	#SET RAN TO 0
	ran=0
fi
done
exit

